package scfg.output.database;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

public class DatabaseLogin {
	
	private HashMap<String, String> variables;
	
	public String getUsername() {
		return variables.get("username");
	}

	public String getPassword() {
		return variables.get("password");
	}

	public String getDbname() {
		return variables.get("DBname");
	}

	public String getHostname() {
		return variables.get("hostname");
	}
	
	public String getFilename(){
		return variables.get("filename");
	}
	
	public String setFilename(String newFilename) {
		String filename = getFilename();
		variables.put("filename", newFilename);
		return filename;
	}

	public DatabaseLogin(){
		this("DBconfig.ini");
	}
	
	public DatabaseLogin(String filename){
		variables = new HashMap<String, String>();
		variables.put("filename", filename);
		readConfigFile();
	}
	
	private void readConfigFile(){
		String filename = variables.get("filename");
		if(filename == null)
			return;
		File f = new File(filename);
		if(!f.exists())
			return;
		try {
			Scanner scan = new Scanner(f);
			String line;
			String[] arr;
			while (scan.hasNextLine()){
				line = scan.nextLine();
				if (line.trim().startsWith("#"))
					return;
				arr = line.split(":");
				if(arr.length == 2){
					variables.put(arr[0].trim(), arr[1].trim());
				}
			}
		} catch (Exception e) {
			// TODO: report file not found exception
		}
	}
	
	public boolean writeToFile(){
		try {
			BufferedWriter bf = new BufferedWriter(new FileWriter(new File(variables.get("filename"))));
			bf.write("#Auto-Generated Database Configuration File\n\n");
			for (Entry<String, String> me : variables.entrySet()){
				if (me.getKey() != null && me.getValue() != null) {
					bf.write(me.getKey());
					bf.write(": ");
					bf.write(me.getValue());
					bf.write("\n");
				}
			}
		} catch (Exception e) {
			
		}
		return false;
	}
}
